#include "FileTest.h"
#include <stdio.h>
#include <string.h>

/*
 * Created: 2/27/12; CGP
 
a) Create a new file (opened for writing)
b) Write multiple bytes of data into the file
c) Close the file
d) Open the same file, for writing
e) Write multiple additional bytes of data into the file (should append)
f) Close the file
g) Open the same file for reading
h) Read all the data & verify that the data was the same as expected. That is, the data from *both* the first and second write should be present in the file.
i) Make sure that when you read past the end of the file, you can't read more data. (i.e., End of File is detected correctly).
 */

#define NUMBER_WRITES 1

int main() {
    int length;
    printf("Starting test...\n"); fflush(stdout);
    FileTest ft;
    const char *fileName = "test1";

    File *f1 = new File(fileName, "w");
    unsigned char data[] = "abcdefghijklmnopqrstuvwxyz";
    int dataLength = strlen((const char *) data)+1;
    for (int i=0; i < NUMBER_WRITES; i++) {
        length = f1->Write(data, dataLength);
    }
    if (! f1->Close()) {
        printf("ERROR: Could not close file\n");
    }
    delete f1;

    f1 = new File(fileName, "w");
    for (int i=0; i < NUMBER_WRITES; i++) {
        length = f1->Write(data, dataLength);
    }
    if (! f1->Close()) {
        printf("ERROR: Could not close file\n");
    }
    delete f1;

#define NUMBER_READS 2
    f1 = new File(fileName, "r");
    unsigned char buffer[100];
    for (int i=0; i < NUMBER_READS; i++) {
        length = f1->Read(buffer, dataLength);
        
        if (length != dataLength) {
            printf("ERROR: Could not read back all %d bytes of file\n", dataLength);
        }
        
        if (strcmp((const char *) data, (const char *) buffer) != 0) {
            printf("ERROR: Buffer (= %s) is not equal to data written (= %s)\n", buffer, data);
        }
    }

    length = f1->Read(buffer, 1);
    if (length != 0) {
        printf("ERROR: End of file not correctly reached (read returned= %d)\n", length);
    }

    if (! f1->Close()) {
        printf("ERROR: Could not close file\n");
    }
    delete f1;
}




